Ext.define('Projeto.controller.Image', {
    extend: 'Ext.app.Controller',
       
    stores: ['Images', 'Observatories'],
    
    refs: [{
    	ref: 'imageWindow', selector: 'imageedit'
    },{
    	ref: 'cboTipo', selector: 'imageedit > form > combobox[id=cboTipoImagem]',
    },{
    	ref: 'uploadField', selector: 'imageedit > form > filefield[name=image]',
    },{
    	ref: 'gridImages', selector: 'imageslist',    	
    },{
    	ref: 'fromDate', selector: 'imagefilter > fieldset > datefield[name=from_date]',    	
    },{
    	ref: 'toDate', selector: 'imagefilter > fieldset > datefield[name=to_date]'    	
    }],
    
    init: function() {
        this.control({
        	'imageslist': {
        		render: this.onListRender,
        		beforerender: function(grid) {
        			if (this.application.currentUser.nivelId == 2) {
        				grid.columns[5].hidden = true;        				
        			}
        		},
        		itemdblclick: this.onItemClick
        	},
        	
            'imageslist > toolbar > button[action=new]' : {
                click: this.newImage
            },
            
            'imageslist > toolbar > button[action=download]' : {
                click: this.onDownloadSelectedImages,
            },
            
            'imageedit > form > toolbar > button[action=save]': {
            	click: this.onUpload
            },
            
            'imageedit': {
            	imagesLoad: this.onReloadImages,
            	saveImage: this.onSaveImage
            },
            
            'imageedit > form > container[id=containerUpload]': {
            	afterrender: function() {
            		Ext.defer(function(){
				        $('#containerUpload').uploadify({
							'uploader'  : '../resources/uploadify/uploadify.swf',
							'script'    : 'image/upload/',
							'cancelImg' : '../resources/uploadify/cancel.png',
							'folder'    : '../resources/',
							'auto'      : false,
							'multi': true,
							onInit: function() {
								uploadify = this;
							},
							onAllComplete: function() {
								var window = Ext.getCmp('imageWindow');
								window.fireEvent('saveImage');
							}
						});
            		}, 500);
            	}
            },
            
            'imagefilter > fieldset > button[action=filter]': {
            	click: this.onFilter
            },
            
            'imagefilter': {
            	render: this.onImageFilterRender
            },
            
            'imagefilter > fieldset > datefield[name=from_date]': {
            	render: function(obj) {
            		obj.setRawValue('');
            		obj.setValue('');
            	}
            },
            
            'imagefilter > fieldset > datefield[name=to_date]': {
            	render: function(obj) {
            		obj.setRawValue('');
            		obj.setValue('');
            	}
            }
    
        });
        
    },
    
    onImageFilterRender: function() {
    	this.getObservatoriesStore().load();
    },
    
    onDownloadSelectedImages: function() {
    	var imagesSelected = this.getGridImages().getSelectionModel().getSelection();
    	
    	if (imagesSelected.length > 0) {
    		var param = new Array();
    		for (var i = 0; i < imagesSelected.length; i++) {
    			param.push(imagesSelected[i].get('caminho'));
    		}
    		
    		window.location = "image/download?param=" + param.join('|');    		
    	} else {
    		Ext.Msg.alert('Erro', 'Selecione pelo menos uma mensagem!');
    	}
    	
    },

    newImage: function() {
        var view = Ext.widget('imageedit');
        view.show();
    },
    
    onReloadImages: function() {
    
    },
    
    onItemClick: function(view, record, item, index, event, opts) {
    	var view = Ext.widget('imageedit');
    	var form = view.down('form');
    	
    	this.getUploadField().setVisible(false);
    	
    	form.loadRecord(record);
    	this.getCboTipo().setRawValue(record.get('tipo'));
    },
    
    onListRender: function() {
    	this.getImagesStore().load(function() {
    		$("a.imagens").fancybox();
    	});
    },
    
    onSaveImage: function() {
    	var window = this.getImageWindow();
    	var form = window.down('form');
    	var record = form.getRecord();
    	var values = form.getValues();
    	
    	var me = this;
    	
    	Ext.Ajax.request({
    	    url: 'image/saveImages/' + values.tipo + '/' + values.obs,
    	    success: function(response){
    	        var text = response.responseText;
    	        if (text == '1') {    	        	
    	        	window.close();
    	        	me.getImagesStore().load();
    	        }
    	    }
    	});
    },
    
    
    onUpload: function() {
    	$('#containerUpload').uploadifyUpload();    		
    	
    },
    
    onFilter: function(btn) {
    	var form = btn.up('form');
    	var proxy = this.getImagesStore().getProxy();
    	
    	delete proxy.cacheString;
    	proxy.extraParams = form.getValues();
    	this.getImagesStore().load();
    }
});